var debug = new Array();

$().ready(function() {
	$('body')
		.ajaxComplete(function(event, XMLHttpRequest, ajaxOptions){
			var expr = new RegExp('tmpl', 'i');
			var textFind = ajaxOptions.url.search(expr) != -1;
			if (!textFind) {			
				try {
					var jsonText = $.parseJSON(XMLHttpRequest.responseText);
					debug[debug.length] = jsonText.debug;
				}
				catch (e) {
					debug[debug.length] = new Object();
					debug[debug.length - 1]['trace'] = XMLHttpRequest.responseText;
				}
				if (debug[debug.length - 1] != undefined)  {
					debug[debug.length - 1]['name'] = ajaxOptions.url;
					debug[debug.length - 1]['post'] = ajaxOptions.data;
					debug[debug.length - 1]['result'] = XMLHttpRequest.responseText;
				}
			}
		});
	$('.debugCollapse').live('click', function(){
		if ($(this).next().is(':visible')) {
			$(this).next().hide();
			if ($(this).text().substr(0, 1) == '–')	$(this).text('+' + $(this).text().substr(1));
		}
		else {
			$(this).next().show();
			if ($(this).text().substr(0, 1) == '+')	$(this).text('–' + $(this).text().substr(1));
		}
	});	
});

function jDebug() {
	if ($('#jDebug:visible').length) $('#jDebug').remove();
	else {
		var retText = '';
		for (var i = 0; i < debug.length; i++) {
			retText += '<p class="debugCollapse"><b>+ ' + debug[i]['name'] + '</b></p>';
			retText += '<div class="debugHidden">';
			retText += debug[i]['trace'];
			retText += '</div>';
		}
		$('body').append('<div id="jDebug"></div>');
		$('#jDebug').append( retText );		
		$('.debugHidden').hide();
	}
	
}